/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jhotdraw.samples.phototemplate;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

/**
 * Jersey REST client generated for REST resource:GenericResource [generic]<br>
 * USAGE:
 * <pre>
 *        NewJerseyClient client = new NewJerseyClient();
 *        Object response = client.XXX(...);
 *        // do whatever with response
 *        client.close();
 * </pre>
 *
 * @author Eliazar
 */
public class WebServiceClient {

    private Client client;
    private String servicePath;

    public WebServiceClient(String path) {
        this.servicePath = path;
    }

    public String getRecord() throws Exception {
        StringBuilder responseData = new StringBuilder();
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(servicePath);
        HttpResponse response1 = httpclient.execute(httpget);
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            InputStream stream = entity1.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            String line = null;
            while ((line = br.readLine()) != null) {
                responseData.append(line);
            }
            EntityUtils.consume(entity1);
        } finally {
            httpget.releaseConnection();
        }
        return responseData.toString();
    }

    public Map<String, String> getRecordMap() throws Exception {
        checkAllNecessityInformation();
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String proxy = Utilities.getProperty(Utilities.KEY.PROXY);
        if (Boolean.valueOf(proxy)) {
            setProxyConfiguration(httpclient);
        }
        HttpGet httpget = new HttpGet(servicePath);
        HttpResponse response1 = httpclient.execute(httpget);
        Map<String, String> map = new HashMap<String, String>();
        try {            
            HttpEntity entity1 = response1.getEntity();
            InputStream stream = entity1.getContent();
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(new InputStreamReader(stream));
            Element root = document.getRootElement();
            Iterator<Element> it = root.getChildren().iterator();            
            Element element;
            while (it.hasNext()) {
                element = it.next();
                map.put(element.getName(), element.getTextTrim());
            }
            EntityUtils.consume(entity1);
        } finally {
            httpget.releaseConnection();
        }
        return map;
    }

    public void close() {
        client.destroy();
    }

    private void checkAllNecessityInformation() throws Exception {
        String urlService = Utilities.getProperty(Utilities.KEY.URL_SERVICE);
        String passwordWebService = Utilities.getProperty(Utilities.KEY.SENHA_WEB_SERVICE);
        String proxy = Utilities.getProperty(Utilities.KEY.PROXY);
        StringBuilder sb = new StringBuilder("");
        if (urlService == null || urlService.trim().equals("")) {
            sb.append("Informe a URI do serviço web \n");
        }
        if (passwordWebService == null || passwordWebService.trim().equals("")) {
            sb.append("Informe a senha utilizada para gerar o token de acesso ao serviço web \n");
        }
        if (proxy != null && Boolean.valueOf(proxy)) {
            String urlProxy = Utilities.getProperty(Utilities.KEY.URL_PROXY);
            String port = Utilities.getProperty(Utilities.KEY.PORTA);
            if (urlProxy == null || urlProxy.trim().equals("")) {
                sb.append("\tInforme a URI do proxy \n");
            }
            if (port == null || port.trim().equals("")) {
                sb.append("\tInforme a porta de acesso ao proxy \n");
            }
        }
        if (!sb.toString().equals("")) {
            throw new WebServiceException("Dados necessários para realizar essa operação: \n" + sb.toString());
        }
    }

    private void setProxyConfiguration(DefaultHttpClient httpClient) {
        String login = Utilities.getProperty(Utilities.KEY.LOGIN);
        String password = Utilities.getProperty(Utilities.KEY.SENHA);
        if (login != null && !login.trim().equals("")) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(login, password);
            httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
            AuthScope proxyScope = new AuthScope(Utilities.getProperty(Utilities.KEY.URL_PROXY), Double.valueOf(Utilities.getProperty(Utilities.KEY.PORTA)).intValue());
            httpClient.getCredentialsProvider().setCredentials(proxyScope, creds);
        }
        HttpHost proxy = new HttpHost(Utilities.getProperty(Utilities.KEY.URL_PROXY), Double.valueOf(Utilities.getProperty(Utilities.KEY.PORTA)).intValue());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
}
